Skip to main content

su — Switch User Context Safely

Learning Focus

By the end of this lesson, you will be able to switch identities with the correct shell/environment mode, run single commands as another user, and avoid unsafe root-session habits on production WordPress VPS hosts.

Overview

su (substitute user) starts a shell or command as another account. It is useful when you need to test permissions, run maintenance as a service user, or temporarily operate as root from a trusted admin session.

For day-to-day operations, sudo is usually preferred for auditability, but su remains valuable for controlled context switching.

Tool Snapshot
  • Core Function: Change current shell identity to another local user.
  • Primary Benefit: Fast context switching for troubleshooting and user-level validation.
  • Where to Use: Permission testing, service-account checks, controlled root shell tasks.
  • Workflow: su [OPTIONS] [-] [USER [ARG ...]].

su is provided by util-linux (/usr/bin/su) on Ubuntu.

System Check

Ensure su is available and check your version:

which su # Expected: /usr/bin/su
su --version # Shows util-linux version

Syntax & Expression Rules

The command follows a logical structure that reads almost like a sentence:

su [OPTIONS] [-] [USER [ARG ...]]
  • [OPTIONS]: Mode flags like -l, -c, -s, or -m.
  • [-]: Login-shell switch that loads the target user's environment.
  • [USER [ARG ...]]: Target account and optional command arguments.

Context Switching Flags

ExpressionDescriptionExample Syntax⭐ Rating
:--:--:--:--
(no args)Switch to root (prompts root password)su⭐⭐⭐
- USER or -l USERLogin shell as target usersu - www-data⭐⭐⭐⭐⭐
-c "CMD"Run one command as target usersu - www-data -c 'id'⭐⭐⭐⭐⭐
-s SHELLUse specific shell for sessionsu -s /bin/bash deployer⭐⭐⭐
-m / -pPreserve current environment variablessu -m root⭐⭐
--session-commandRun command without new sessionsu --session-command 'id' www-data⭐⭐

Operational Alternatives

ActionDescriptionWordPress/VPS Use CaseExample Syntax
:--:--:--:--
Use login-style context switchFull target user environmentValidate app behavior as www-datasu - www-data
Run one isolated commandNo long-lived shell requiredQuick ownership check as service usersu - www-data -c 'whoami && pwd'
Prefer auditable elevationBetter traceability than shared root passwordTeam operations on production VPSsudo -u www-data wp plugin list --path=/var/www/html
Exit switched shell cleanlyReturn to original identityPrevent accidental command misuseexit

Practical Use Cases

1. Switch to root shell (legacy workflow)

su -

Expected output:

Password:
root@vps:~#

Explanation: Starts a root login shell after root-password authentication. Use case: Recovery scenarios where sudo is unavailable.

2. Switch to web daemon user for permission test

su - www-data

Expected output:

www-data@vps:/var/www$

Explanation: Opens a shell under www-data identity. Use case: Reproduce WordPress write/read behavior exactly as web server user.

3. Run one command as www-data

su - www-data -c 'id'

Expected output:

uid=33(www-data) gid=33(www-data) groups=33(www-data)

Explanation: Executes single command without interactive shell. Use case: Quick scripted verification.

4. Check WordPress path access as service user

su - www-data -c 'test -w /var/www/html/wp-content && echo writable || echo not-writable'

Expected output:

writable

Explanation: Validates effective write permission for web process. Use case: Troubleshoot upload/update failures.

5. Use a specific shell for target user

su -s /bin/bash deployer

Expected output:

deployer@vps:/home/deployer$

Explanation: Overrides target shell for current switch. Use case: Temporary diagnostics when account uses restricted shell.

6. Preserve caller environment (advanced)

su -m root -c 'echo $PATH'

Expected output:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Explanation: Keeps environment variables from calling session. Use case: Controlled test workflows where inherited env is required.

7. Return safely to original identity

whoami && su - www-data -c 'whoami' && whoami

Expected output:

wpadmin
www-data
wpadmin

Explanation: Confirms temporary context switch and clean return. Use case: Avoid running sensitive commands under wrong account.

8. Prefer sudo for audited one-off command

sudo -u www-data -- wp plugin list --path=/var/www/html

Expected output:

+----------------+----------+--------+---------+
| name | status | update | version |
+----------------+----------+--------+---------+

Explanation: Executes as target user with audit logs and policy controls. Use case: Safer production workflow than long-lived su sessions.

Common Mistakes & Troubleshooting

ProblemCauseFix
:--:--:--
su: Authentication failureWrong root/target password or root login disabledUse sudo -i from authorized admin account
Unexpected PATH or home directoryUsed su USER instead of login modeUse su - USER to load target profile
Commands run as wrong user after testingForgot to exit switched shellRun whoami, then exit until back to expected user
Cannot switch to restricted account shellTarget user uses /usr/sbin/nologinRun one command via sudo -u USER CMD instead
No audit trail for shared root password usageTeam uses direct su - habitMove daily ops to sudo with group-based policies

Best Practices

  • Use su - USER for clean context: Login mode avoids mixed environment bugs.
  • Keep su sessions short-lived: Prefer single-command execution where possible.
  • Prefer sudo for production teamwork: It provides better logging and policy control.
  • Verify identity before destructive commands: Run whoami in every switched shell.
  • Avoid shared root passwords: Use per-user accounts plus sudoers policy.

Hands-On Practice

Task: Validate Web-User Access Without Breaking Auditability

  1. Run su - www-data -c 'id && test -w /var/www/html/wp-content && echo writable'.
  2. Repeat the same validation with sudo -u www-data -- ... and compare outputs.
  3. Challenge: Build a small check script that aborts if current identity is not www-data before running file-write tests.

Connection to Other Concepts

  • sudo: Recommended for audited privilege escalation in team operations.
  • id: Confirms active identity before and after switching users.
  • passwd: Manages account credentials used by su authentication.
  • who: Helps monitor active admin sessions during maintenance windows.

Visual Learning Diagram

What's Next: Proceed to sudo — Privilege Escalation with Audit Control to manage elevated commands with safer policy and logging.